package com.zytech.zspider.task.impl.http;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableMap;
import com.zytech.modules.lang.Strings;
import com.zytech.zspider.core.TaskDefinition;
import com.zytech.zspider.task.TaskContext;
import org.apache.commons.codec.binary.Base64;

import java.util.Map;

/**
 * @author siuming
 */
public class WebClientTaskExecutor extends AbstractHttpTaskExecutor {

    public WebClientTaskExecutor() {
        this(DEFAULT_BLOCKING_FACTOR);
    }

    /**
     * @param blockingFactor
     */
    public WebClientTaskExecutor(float blockingFactor) {
        super(
                blockingFactor,
                new String[]{
                        "/spider-task.groovy",
                        "/spider-task-htmlunit.groovy"
                },
                new WebClientTaskRequestExecutor()
        );
    }

    @Override
    protected boolean isHttpTaskSupports(TaskDefinition task, Map<String, String> settings) {
        String executor = settings.get(TaskDefinition.Settings.HTTP_EXECUTOR);
        return Strings.isBlank(executor) || Objects.equal(executor, "executor.webclient");
    }

    @Override
    protected TaskContext ofCollectTaskResultContext(TaskDefinition task, TaskContext context, HttpTaskRequest request, HttpTaskResponse response) {
        if (response.isImageMimeType() || response.isOctetMimeType()) {
            context.putBinding("_$content_type", response.getMimeType());
            context.putBinding("_$content", Base64.encodeBase64String(response.getContent()));
        }

        context.putAllBindings(ImmutableMap.of("_$req", request, "_$resp", response, "_$page", response.getWrapContent()));
        return context;
    }

    @Override
    protected void releaseCollectTaskResultContext(TaskDefinition task, TaskContext context) {
        if (null != WebClientHolder.get()) {
            WebClientHolder.get().closeAllWindows();
        }
    }
}
